package com.xm.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {

    /**
     * 通过 网关路由-转发请求-到服务器
     * 访问 <a href="http://localhost:8081/app01/api/test/1">...</a>
     * 访问 <a href="http://localhost:8081/app02/api/test/1">...</a>
     */
    @Bean
    public RouteLocator customRoute(RouteLocatorBuilder builder) {
        // 访问：http://localhost:8081/app01/api/test http://192.168.119.1:8082/xm-application-01/api/test http://192.168.119.1:8083/xm-application-01/api/test
        // 访问：http://localhost:8081/app02/api/test http://192.168.119.1:8084/xm-application-02/api/test

        return builder.routes()
                // 路由1
                .route("xm-application-01-route", r -> r.path("/app01/api/**")
                        .filters(f -> f.rewritePath("/app01/api/(?<segment>.*)", "/api/${segment}"))
                        .uri("lb://xm-application-01"))
                // 路由2
                .route("xm-application-02-route", r -> r.path("/app02/api/**")
                        .filters(f -> f.rewritePath("/app02/api/(?<segment>.*)", "/api/${segment}"))
                        .uri("lb://xm-application-02"))
                        .build();
    }
}
